<template>
    <el-form ref="form" class="p-vehicle-detail-form" :model="form" :rules="rules" :show-message="!readonly">
        <div class="act-box">
            <!--<el-button @click="handleAction" :class="actClassName">{{ actionName }}</el-button>-->

            <!--继续-->
            <el-button
                v-if="action"
                type="success"
                class="el-icon-video-play"
                size="small"
                @click="handleStart"
            ></el-button>
            <!--停止-->
            <el-button v-else type="warning" class="el-icon-video-pause" size="small" @click="handleStop"></el-button>
        </div>
        <el-collapse :value="defaultOpend" class="detail-collapse">
            <!--action-->
            <!--<el-collapse-item :title="$t('lang.general')" name="0">-->
            <!--<template>-->
            <!--</template>-->
            <!--</el-collapse-item>-->
            <!--general-->
            <el-collapse-item :title="$t('lang.general')" name="1" :class="{ 'hidden-error': form.id }">
                <!--when creat-->
                <template v-if="!readonly">
                    <el-form-item :label="$t('lang.name')" prop="id">
                        <v-text v-if="status !== 'add'" v-model="form.id"></v-text>
                        <!--<el-input v-else v-model="form.id" size="small"></el-input>-->
                        <p-picker-vehicle v-else-if="isShowVehiclePicker" v-model="form.id"></p-picker-vehicle>
                    </el-form-item>
                    <el-form-item :label="$t('lang.location')">
                        <!--陈林芝需求实体车不允许修改路径-新增或者是模拟车时，可编辑，否则不能编辑路径Id---2020.5.13-->
                        <p-picker-path
                            v-if="status === 'add' || form.isSimulated === true"
                            v-model="form.pathId"
                        ></p-picker-path>
                        <v-text v-else v-model="form.pathId"></v-text>
                    </el-form-item>
                    <el-form-item :label="$t('lang.navigatorId')">
                        <el-input v-model="form.navigatorId" size="small"></el-input>
                    </el-form-item>
                </template>
                <!--when preview-->
                <template v-else>
                    <el-form-item :label="$t('lang.name')" prop="id">
                        <v-text v-model="form.id"></v-text>
                    </el-form-item>
                    <!-- <el-form-item :label="$t('lang.location')" prop="pathId">
                        <v-text v-model="form.pathId"></v-text>
                    </el-form-item> -->
                    <template v-if="form.modelExt && form.modelExt.size">
                        <el-form-item :label="$t('lang.vehicleSizeLW')" class="haf" prop="width">
                            <v-text :value="form.modelExt.size.x"></v-text>
                            <v-text value=" | "></v-text>
                            <v-text :value="form.modelExt.size.y"></v-text>
                        </el-form-item>
                    </template>

                    <el-form-item :label="$t('lang.networkAddress')" prop="ip">
                        <v-text :value="form.ip + ':' + form.port" />
                    </el-form-item>
                    <el-form-item :label="$t('lang.firstRegistration')" class="haf" prop="firstTelegramTime">
                        <v-text v-model="form.firstTelegramTimeExt" />
                    </el-form-item>
                </template>
            </el-collapse-item>

            <!--label-->
            <el-collapse-item :title="$t('lang.label')" name="2">
                <el-form-item :label="$t('lang.text')" prop="label">
                    <v-text v-if="readonly" v-model="form.label" />
                    <el-input v-else v-model="form.label" size="small" />
                </el-form-item>
                <el-form-item :label="$t('lang.color')" prop="labelColor">
                    <el-input v-if="!readonly" v-model="form.labelColor" :disabled="labelDisabled" size="small" />
                    <el-color-picker v-model="form.labelColor" :disabled="readonly || labelDisabled" show-alpha />
                    <v-text v-if="readonly" v-model="form.labelColor" :limit="15" />
                </el-form-item>
                <el-form-item :label="$t('lang.offsetXY')" prop="labelOffset">
                    <template v-if="readonly">
                        <v-text :value="form.labelOffset.x + ' px | ' + form.labelOffset.y + ' px'" />
                    </template>
                    <template v-else>
                        <el-input v-model="form.labelOffset.x" :disabled="labelDisabled" size="small" />
                        <el-input v-model="form.labelOffset.y" :disabled="labelDisabled" size="small" />
                    </template>
                </el-form-item>
            </el-collapse-item>

            <!--status-->
            <el-collapse-item
                v-if="readonly && form.statusExt && Object.keys(form.statusExt).length"
                class="detail-status"
                :title="$t('lang.status')"
                name="2"
            >
                <template v-for="(s, k, i) in form.statusExt" :key="'s' + i">
                    <el-form-item :label="k" class="horizontal haf reverse lh24">
                        <!--<div :key="'s' + i">-->
                        <i :class="['icon', s.color ? 'icon-selected ' + s.color : 'icon-select']"></i>
                        {{ typeof s.value == 'number' ? s.value : '' }}
                        <!--</div>-->
                    </el-form-item>
                </template>
            </el-collapse-item>

            <!--errors-->
            <el-collapse-item
                v-if="readonly && form.errorsExt && form.errorsExt.length"
                class="detail-status"
                :title="$t('lang.errors')"
                name="3"
            >
                <template v-for="(e, i) in form.errorsExt" :key="'e' + i">
                    <el-form-item label="" class="horizontal haf reverse">
                        {{ e.datetime }} {{ e.msg }}
                    </el-form-item>
                </template>
            </el-collapse-item>

            <!--remote-->
            <el-collapse-item v-if="readonly && form.isOnline" :title="$t('lang.remote')" name="4">
                <p-vehicle-remote-detail :id="form.id" :form="form" />
            </el-collapse-item>

            <!--IO-->
            <el-collapse-item v-if="readonly && (form.rawInput || form.rawOutput)" :title="$t('lang.io')" name="5">
                <div class="vehicle-io" v-if="vehicleIO.length > 0">
                    <span v-for="(tagName, idx) in vehicleIO" :key="'tag' + idx">{{ tagName }}</span>
                </div>
                <p-vehicle-io-detail :value="this.form.ioExt" />
            </el-collapse-item>
        </el-collapse>
        <!--buttons-->
        <p-detail-buttons :compact="compact" :submit-func="submit" :readonly="readonly"></p-detail-buttons>
    </el-form>
</template>

<script type="text/ecmascript-6">
import { mapState } from 'vuex';
import * as API from '../../../core/api.js';
import * as Chef from '../../../core/Chef.js';
import bus from '../../../utils/Eventbus.js';
import * as enums from '../../../store/status-enums.js';
import vText from '../../../utils/v-text.vue';
import pVehicleIoDetail from './p-vehicle-io-detail.vue';
import pVehicleRemoteDetail from './p-vehicle-remote-detail.vue';
import pDetailButtons from '../p-detail-buttons.vue';
import pPickerPath from '../../../components/p-picker-path.vue';
import pPickerVehicle from '../../../components/p-picker-vehicle.vue';
import i18n from '../../../lang/index.js';
const $t = i18n.global.t;

export default {
    name: 'p-vehicle-detail-form',
    components: { vText, pVehicleIoDetail, pVehicleRemoteDetail, pDetailButtons, pPickerPath, pPickerVehicle },
    props: {
        id: String,
        ids: Array,
        value: Object,
        status: String,
        compact: Boolean,
        readonly: Boolean
    },
    data() {
        return {
            vehicleIO: ['INPUT(TARGET > SERVER)', 'OUTPUT(TARGET > SERVER)'],
            form: { labelOffset: { x: 0, y: 0 } },
            rules: {
                id: [{ required: true, message: $t('lang.id') + ' ' + $t('lang.required') }]
                // 王大嵩有引导车Id时，路径为非必填 2020-04-26
                // pathId: [{ required: true, message: $t('lang.location') + ' ' + $t('lang.required'), trigger: 'blur' }]
            },
            defaultOpend: ['1', '2', '4', '5'],
            pathOptions: [],
            isShowVehiclePicker: true,
            action: false,
            actionName: '停止',
            actClassName: 'red'
        };
    },
    computed: {
        ...mapState({
            floaterTag: state => state.app.floaterOpened
        }),
        labelDisabled() {
            return !this.form.label;
        }
    },
    watch: {
        // id: { handler () { this.init(); }, deep: true },
        // ids: { handler () { this.init(); }, deep: true },
        ids() {
            this.init();
        },
        value: {
            handler(val) {
                this.form = val;
            }, deep: true
        },
        form(val) {
            this.$emit('input', val);
        },
        '$root.ws.serverTime'() {
            this.initAsync();
        }
    },
    mounted() {
        this.init();
    },
    beforeDestroy() {
        if (this.timer) clearTimeout(this.timer);
    },
    methods: {
        init() {
            console.log('p-vehicle-detail-form.init: ', this.ids[0]);
            // if (this.id) this.getDetail(this.id);
            // if (this.ids.length === 1) this.getDetail(this.ids[0]);
            // if (this.ids.length > 1) this.getDetails(this.ids);
            if (this.ids.length === 1 && this.ids[0] === -1) {
                this.form = { labelOffset: { x: 0, y: 0 } };
            } else if (this.ids.length) {
                this.isShowVehiclePicker = false;
                this.getDetails(this.ids).then(res => {
                    if (!res) return;
                    Chef.extendVehicle(res);
                    Chef.extendVehicleIO(res);
                    // Chef.extendVehicleStatus(res);
                    this.form = res;
                    this.isShowVehiclePicker = true;

                    // console.error('222', this.form.properties);
                    if (this.form.properties && this.form.properties.stop && this.form.properties.stop === 'true') {
                        this.action = true;
                        this.actionName = '继续';
                        this.actClassName = 'green';
                    } else {
                        this.action = false;
                        this.actionName = '停止';
                        this.actClassName = 'red';
                    }
                }).catch(() => {
                });
            } else this.form = { labelOffset: { x: 0, y: 0 } };
            this.getPathsOptions();
        },
        initAsync() {
            Chef.extendVehicleIO(this.form, this.$root.resources.vehicles);
            Chef.extendVehicleErrors(this.form, this.$root.resources.vehicles, this.$root.resources.models, this.$root.ws.serverTime);
        },
        // 车辆继续 --add by ouyang on 2020.08.17
        handleStart(e) {
            let act = true;
            act = !act;
            // console.warn('DO-ACT: ', e, this.action);
            let params = [{
                body: `${act}`,
                method: 'PUT',
                path: `/vehicles/${this.form.id}/stop`
            }];
            // bus.emit('p-table.init');
            API.updateVehicleStop(params, { button: e.target || e.srcElement })
                .then(() => {
                    this.action = act;
                    // bus.emit('p-table.init');
                })
                .catch(() => {
                });
        },
        // 车辆停止 --add by ouyang on 2020.08.17
        handleStop(e) {
            let act = false;
            act = !act;
            // console.warn('DO-ACT: ', e, this.action);
            let params = [{
                body: `${act}`,
                method: 'PUT',
                path: `/vehicles/${this.form.id}/stop`
            }];
            // bus.emit('p-table.init');
            API.updateVehicleStop(params, { button: e.target || e.srcElement })
                .then(() => {
                    this.action = act;
                    // bus.emit('p-table.init');
                })
                .catch(() => {
                });
        },
        getPathsOptions() {
            if (!this.$root.resources || !this.$root.resources.paths || !this.$root.resources.paths.length)
                return this.timer = setTimeout(this.getPathsOptions, 200);
            this.pathOptions = Chef.getPathsOptions(this.$root.resources.paths);
        },
        getDetails(ids) {
            // TODO: mod some property to '?'
            return API.filterLocalResources('vehicles', ids).then(res => Chef.combineVehicle(res.list));
        },

        isRepeat(id) {
            if (this.status === 'add' && this.$root.resources && this.$root.resources.vehicles && this.$root.resources.vehicles.length > 0) {
                return this.$root.resources.vehicles.some(item => {
                    return item.id === id;
                });
            } else {
                return false;
            }
        },
        submit(e) {
            console.log('p-vehicle-detail-form.handleSubmit: ', e);
            // 新增判断列表中有没有重复的id
            if (this.isRepeat(this.form.id)) {
                this.$message.error($t('lang.nameRepeat'));
                return Promise.reject($t('lang.nameRepeat'));
            }
            return this.$refs.form.validate().then(valid => {
                if (valid) {
                    // 清除车辆id 引导车id中的空格.replace(/\s*/g, ''),
                    let form = {
                        id: this.form.id,
                        pathId: this.form.pathId,
                        navigatorId: this.form.navigatorId,
                        label: this.form.label,
                        labelColor: this.form.labelColor,
                        labelOffset: this.form.labelOffset
                    };
                    if (form.id) form.id = form.id.replace(/\s*/g, '');
                    if (form.navigatorId) form.navigatorId.replace(/\s*/g, '');
                    return API.updateVehicle(form, e.target || e.srcElement).then(res => {
                        console.log('p-vehicle-detail-form.submit.success: ', res);
                        bus.emit('p-table.init');
                        this.$store.commit(enums.DESELECT_VEHICLES_ALL);
                        // if (this.compact) bus.emit('p-panel.editEnableChange', false);
                        if (this.compact) {
                            bus.emit('p-panel.editEnableChange', false);
                            bus.emit('vehicles.toggleRowSelection', []);
                            this.$store.commit(enums.OPEN_BOX_SINGLETON, 'vehiclesTable');
                        }
                    });
                } else {
                    let msg = $t('lang.submitError');
                    this.$message.error(msg);
                    return Promise.reject(msg);
                }
            });
        }
    }
};
</script>

<style lang="scss">
.p-vehicle-detail-form {
    .act-box {
        width: 100%;
        height: 48px;
        display: flex;
        justify-content: flex-end;
        align-items: center;

        .el-icon-video-play {
            margin-right: 8px;
            padding: 6px 6px;
        }

        .el-icon-video-pause {
            margin-right: 8px;
            padding: 6px 6px;
        }

        /*.el-button {*/
        /*    font-size: 14px;*/
        /*    color: #fff;*/
        /*}*/

        /*.el-button:hover {*/
        /*    border-color: gray;*/
        /*    -webkit-box-shadow: 0 0 3px grey;*/
        /*    box-shadow: 0 0 3px grey;*/
        /*    -webkit-transition: color 100ms, background-color 100ms, border-color 100ms, -webkit-box-shadow 100ms;*/
        /*    transition: color 100ms, background-color 100ms, border-color 100ms, -webkit-box-shadow 100ms;*/
        /*    transition: color 100ms, background-color 100ms, border-color 100ms, box-shadow 100ms;*/
        /*    transition: color 100ms, background-color 100ms, border-color 100ms, box-shadow 100ms,*/
        /*        -webkit-box-shadow 100ms;*/
        /*    !*border-color: rgba(0, 0, 0, 0);*!*/
        /*    color: #fff;*/
        /*}*/

        /*.red {*/
        /*    background: rgba(255, 20, 0, 0.5);*/
        /*}*/

        /*.green {*/
        /*    background: #67c23a;*/
        /*}*/
    }

    .vehicle-io {
        width: 100%;
        display: flex;
        justify-items: center;
        align-items: self-start;

        span {
            flex: 1;
        }
    }

    .detail-status {
        .el-form-item__content,
        .icon {
            padding: 0 6px 0 0;
        }
        .el-form-item__content {
            line-height: 24px;
        }
    }

    .vehicle-log-button {
        text-align: right;
        padding: 10px;
    }

    .hidden-error {
        .is-error {
            .el-form-item__error {
                display: none;
            }
        }
    }
}
</style>
